/*
 *  (C) Copyright 2008 Insula Tecnologia da Informacao Ltda.
 * 
 *  This file is part of Vulcano.
 *
 *  Vulcano is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Vulcano is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Vulcano.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.openinsula.vulcano.flex.example.controller;

import static org.junit.Assert.*;

import java.util.List;

import org.hibernate.LazyInitializationException;
import org.junit.Test;
import org.openinsula.vulcano.flex.AbstractFlexHibernateTestCase;
import org.openinsula.vulcano.flex.controller.LazyAssociationLoader;
import org.openinsula.vulcano.flex.example.persistence.EntityFactory;
import org.openinsula.vulcano.flex.example.persistence.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.NotTransactional;

public class UserControllerTestCase extends AbstractFlexHibernateTestCase {

	@Autowired
	private UserController userController;

	@Autowired
	private LazyAssociationLoader lazyLoader;

	@Test
	@NotTransactional
	public void testListAllUsers() {
		List<User> listAllUsers = userController.listAllUsers();

		for (User user : listAllUsers) {
			assertNull(user.getRoles());
			assertNull(user.getPerson().getDepartment().getEmployees());
		}

		for (User user : listAllUsers) {
			lazyLoader.initialize(user, "roles");

			try {
				user.getRoles().size();
			}
			catch (LazyInitializationException e) {
				fail("Unexpected LazyInitializationException");
			}

		}
	}

	@Test
	@NotTransactional
	public void testSaveUser() {
		User user = EntityFactory.createUser("testcase", "testcase");
		
		// Since there is no Integer type in AS3 (only primitive int),
		// newly instances will receive 0 for both id and version fields
		user.setId(0);
		user.setVersion(0);
		
		// expecting save operation
		userController.saveUser(user);
		assertTrue(user.getId() > 0);
		assertTrue(user.getVersion() == 0);
		
		// expecting update operation
		userController.saveUser(user);
		assertTrue(user.getVersion() == 1);
	}
}
